import 'dart:convert';

/**
 *
 * @Description:     此类为获取定位相关类,此类与android / ios 交互,修改要联系作者
 * @Author:          胡凯
 * @CreateDate:      2020-08-10
 * @Version:         1.0
 *
 */
import 'package:flutter/services.dart';
import 'package:o_amap/aMapModule/common/latlng.dart';

import 'location.dart';
import 'location_client_options.dart';


class AMapLocation {
  static AMapLocation _instance;

  AMapLocation._();

  factory AMapLocation() {
    if (_instance == null) {
      _instance = AMapLocation._();
      return _instance;
    } else {
      return _instance;
    }
  }

  //  与原生通讯通道
  static const _perform = const MethodChannel("com.p595263720.zit/location");
  static const EventChannel _perform_receive =
      const EventChannel("com.p595263720.zit/location_receive");

  //坐标类型，作为坐标转换使用
  static final int ALIYUN = 0; //阿里云坐标
  static final int BAIDU = 1; //百度坐标
  static final int GOOGLE = 2; //谷歌坐标
  static final int GPS = 3; //GPS原始坐标
  static final int MAPABC = 4; //图盟坐标
  static final int MAPBAR = 5; //图吧坐标
  static final int SOSOMAP = 6; //搜索坐标

  // 只定位一次 默认为只调用一次
  Future<Location> getLocation(LocationClientOptions options) async {
    _perform.invokeMethod("startLocation",{'options': options.toJsonString()});
    Location location = await _perform_receive
        .receiveBroadcastStream()
        .map((result) => result as String)
        .map((resultJson) => Location.fromJson(jsonDecode(resultJson)))
        .first;
    return location;
  }

  // 获取用户位置, 持续定位,interval 表示间隔时间 每个多长时间获取一次 默认3000 （3s）,
  // 如果持续获取过程调用单次获取，需重新调用此方法进行启动
  Stream<Location> startLocation(LocationClientOptions options) {
    _perform.invokeMethod("startLocation",{'options': options.toJsonString()});
    return _perform_receive
        .receiveBroadcastStream()
        .map((result) => result as String)
        .map((resultJson) => Location.fromJson(jsonDecode(resultJson)));
  }

  //  停止定位, 应用于持续定位使用
  Future<Null> stopLocation() async {
    await _perform.invokeMethod("stopLocation");
  }

  // 当不实用定位时，销毁定位, 开始时重新创建定位类
  Future<Null> destroyLocation() async {
    await _perform.invokeMethod("destroyLocation");
  }

  // 坐标转换 实现各种类型坐标转换成高德坐标   coordinateType 坐标类型参数本类常量
  Future<LatLng> coordinateTransformation(
      int coordinateType, LatLng point) async {
    String jsonRes = await _perform.invokeMethod("coordinateTransformation", {
      'coordinateType': coordinateType,
      'latitude': point.latitude,
      'longitude': point.longitude
    });
    return LatLng(jsonDecode(jsonRes)['latitude'],jsonDecode(jsonRes)['longitude']);
  }

  //计算两点间距离 单位 米
  Future<num> calculateLineDistance(
      LatLng start, LatLng end) async {
    num dic = await _perform.invokeMethod("calculateLineDistance", {
      "startLng": start.longitude,
      "startLat": start.latitude,
      "endLng": end.longitude,
      "endLat": end.latitude
    });
    return dic;
  }
}
